package com.wfl.sampling.handler;

import com.alibaba.fastjson2.JSON;
import com.wfl.sampling.aop.NoAuth;
import com.wfl.sampling.entity.Result;
import com.wfl.sampling.utils.JwtUtils;
import org.hibernate.annotations.Comment;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//拦截器使用，放入mvc配置中
@Component
public class LoginHandler implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //方法执行之前进行拦截
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        if(handlerMethod.hasMethodAnnotation(NoAuth.class)){
            return true;
        }
        String token = request.getHeader("Authorization");
        try {
            JwtUtils.parseJwt(token);
        } catch (Exception e) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(Result.error("未登录")));
            return false;
        }
        return true;
    }
}
